<template>
  <view class="comment-list-page">
    <up-navbar title="我的评论" :bgColor="bgColor" leftIcon="arrow-left" @leftClick="handleBack" fixed placeholder>
    </up-navbar>

    <!-- 评论列表 -->
    <scroll-view class="comment-list-container" scroll-y @scrolltolower="handleScrollToLower" :refresher-enabled="true">
      <view class="comment-item" v-for="(item, index) in commentList" :key="item.id">
        <!-- 使用uview-plus的左滑删除组件 -->
        <up-swipe-action>
          <up-swipe-action-item :options="[{ text: '删除', style: { backgroundColor: '#ff4d4f' } }]"
            @click="() => handleSwipeClick(item.id)">
            <!-- 评论内容 -->
            <view class="comment-content">
              <!-- 用户头像 -->
              <view class="user-avatar">
                <up-avatar :src="item.avatar || defaultAvatar" size="36" shape="circle"></up-avatar>
              </view>

              <!-- 评论主体区域 -->
              <view class="comment-main">
                <!-- 用户名和时间 -->
                <view class="user-info">
                  <text class="username">{{ item.nickname || '匿名用户' }}</text>
                  <text class="time">{{ formatTime(item.createTime) }}</text>
                </view>

                <!-- 评论内容和作品信息的左右布局 -->
                <view class="content-work-container">
                  <!-- 左侧：评论文字内容和图片 -->
                  <view class="comment-left">
                    <view class="comment-text">
                      <text>{{ item.content }}</text>
                    </view>
                  </view>

                  <!-- 右侧：关联的作品信息 -->
                  <view class="related-artwork">
                    <view class="artwork-info">
                      <image src="https://picsum.photos/80/80?random=6" mode="aspectFill" class="artwork-thumb"></image>
                      <view class="artwork-text">
                        <text class="artwork-title">999999</text>
                        <text class="artwork-author">999999999</text>
                      </view>
                    </view>
                  </view>
                </view>

                <!-- 底部：点赞数量等操作 -->
                <view class="comment-footer">
                  <view class="like-info">
                    <up-icon name="thumb-up" size="16" :color="item.isLiked ? '#ff0202' : '#999'"></up-icon>
                    <text class="like-count" :class="{ liked: item.isLiked }">{{ item.likeCount }}</text>
                  </view>
                </view>
              </view>
            </view>
          </up-swipe-action-item>
        </up-swipe-action>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="commentList.length === 0 && !loading">
        <up-icon name="chat" size="48" color="#ccc"></up-icon>
        <text class="empty-text">暂无评论</text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 加载完成状态 -->
      <view class="finished-state" v-if="isLastPage && commentList.length > 0 && !loading">
        <text class="finished-text">没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { usePagination } from 'alova/client'
import Apis from '@/api'

// 页面数据
const bgColor = ref('#fff')

// 默认头像
const defaultAvatar = "https://picsum.photos/80/80?random=6"

const pagination = usePagination((page, pageSize) => Apis.wx_comment.listComment({
  params: { pageNum: page, pageSize }
}), {
  initialData: { // 初始数据
    total: 0,
    data: []
  },
  append: true, // 是否追加数据，默认为false
  initialPage: 1, // 初始页码，默认为1
  initialPageSize: 10, // 初始每页数据条数，默认为10
  total: res => res.total, // 从响应中获取总量（默认取total字段）
  data: res => res.rows, // 从数据中获取data（默认取data字段）
})

const {
  update, // 更新状态
  data: commentList, // 数据
  isLastPage, // 根据total和size计算，如果没有total根据当前页数据是否满足size判断
  total, // 总条数
  page, // 当前页码
  pageCount, // 总页数
  loading, // 加载状态
} = pagination

// 格式化时间
const formatTime = (time) => {
  if (!time) return "刚刚"

  // 如果是时间戳，转换为日期对象
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  // 小于1分钟显示刚刚
  if (diff < 60 * 1000) {
    return "刚刚"
  }

  // 小于1小时显示分钟数
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }

  // 小于24小时显示小时数
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }

  // 小于30天显示天数
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }

  // 其他情况显示日期
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`
}

// 处理返回
const handleBack = () => {
  uni.navigateBack()
}

// 处理上拉加载更多
const handleScrollToLower = () => {
  if (!isLastPage.value) {
    page.value++
  }
}

// 处理左滑操作点击
const handleSwipeClick = (id) => {
  // 根据选项索引处理不同操作，这里只有删除操作
  deleteCommentById(id)
}

// 删除评论
const deleteCommentById = async (id) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条评论吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用API删除评论
          const response = await Apis.wx_comment.deleteComment({ data: { id: id } });
          if (response && response.code === 200) {
            uni.showToast({
              title: "删除成功",
              icon: "success"
            });
            pagination.refresh()
          } else {
            uni.showToast({
              title: response.msg || "删除失败",
              icon: "none"
            });
          }
        } catch (error) {
          console.error('删除评论异常:', error)
          uni.showToast({
            title: '删除异常',
            icon: 'none'
          })
        }
      }
    }
  })
}

</script>

<style lang="scss" scoped>
.comment-list-page {
  min-height: 100vh;
  background-color: #eff0f2;
}

.comment-list-container {
  padding: 0 10rpx;
  height: calc(100vh - 44px);
  padding: 10rpx 10rpx 36rpx;
}

.comment-item {
  margin-bottom: 10rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  margin-right: 20rpx;
}

.comment-content {
  display: flex;
  padding: 10rpx;
  background-color: #fff;
  min-height: 100rpx;
}

.user-avatar {
  margin-right: 20rpx;
  flex-shrink: 0;
}

.comment-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 5rpx;

  .username {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }

  .time {
    font-size: 22rpx;
    color: #999;
  }
}

.content-work-container {
  display: flex;
  gap: 15rpx;
  flex: 1;
}

.comment-left {
  flex: 1;
  min-width: 0;
}

.comment-text {
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 10rpx;
  word-wrap: break-word;
}

.related-artwork {
  border-left: 1rpx solid #f0f0f0;
  padding: 10rpx 0 10rpx 15rpx;
  align-self: flex-start;
  flex-shrink: 0;
  width: 180rpx;
}

.artwork-info {
  display: flex;
  align-items: center;
  gap: 10rpx;
  min-width: 0;
}

.artwork-thumb {
  width: 60rpx;
  height: 60rpx;
  border-radius: 6rpx;
  object-fit: cover;
  flex-shrink: 0;
}

.artwork-text {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.artwork-title {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 4rpx;
}

.artwork-author {
  font-size: 20rpx;
  color: #999;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10rpx;
  border-top: 1rpx solid #f0f0f0;
}

.like-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.like-count {
  font-size: 24rpx;
  color: #999;

  &.liked {
    color: #ff0202;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  gap: 10rpx;

  .loading-text {
    font-size: 24rpx;
    color: #999;
  }

  .loading-spinner {
    width: 30rpx;
    height: 30rpx;
    border: 2rpx solid #f3f3f3;
    border-top: 2rpx solid #ff0202;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

.finished-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;

  .finished-text {
    font-size: 24rpx;
    color: #999;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>